package com.paobuji.aidebao.myapplication.ui;

import android.Manifest;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.jaeger.library.StatusBarUtil;
import com.paobuji.aidebao.myapplication.MainActivity;
import com.paobuji.aidebao.myapplication.R;
import com.paobuji.aidebao.myapplication.activity.BaseActivity;
import com.paobuji.aidebao.myapplication.bean.BluResult;
import com.paobuji.aidebao.myapplication.ble.adapter.DeviceAdapter;
import com.paobuji.aidebao.myapplication.ble.entity.EntityDevice;
import com.paobuji.aidebao.myapplication.ble.service.BLEService;
import com.paobuji.aidebao.myapplication.ble.utils.BluetoothController;
import com.paobuji.aidebao.myapplication.ble.utils.ConstantUtils;
import com.paobuji.aidebao.myapplication.ble.utils.Util;
import com.paobuji.aidebao.myapplication.tool.ACache;
import com.paobuji.aidebao.myapplication.tool.BluDataUtil;
import com.paobuji.aidebao.myapplication.tool.Default;
import com.paobuji.aidebao.myapplication.tool.ProgressDialog;
import com.paobuji.aidebao.myapplication.tool.SharedPrefsUtil;

import java.text.DecimalFormat;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MySportActivity extends BaseActivity {

    @BindView(R.id.blueList)
    ListView blueList;
    private ArrayList<EntityDevice> list = new ArrayList<>();
    BluetoothAdapter mAdapter;             //蓝牙适配器

    DeviceAdapter deviceAdapter;
    BluDataUtil bluDataUtil = new BluDataUtil();
    BluResult bluResult;
    Util u = new Util();
    private MsgReceiver receiver;

    Intent intentService;




    ProgressDialog progressDialog;

    ACache aCache;
    int dataNum = 0;
    boolean flag = false;
    String model = null;

    Context context;

    private final int REQUEST_LOCATION_PERMISSION = 1;
    private final int REQUEST_BLE_PERMISSION = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_sport);
        ButterKnife.bind(this);
        context = getApplicationContext();
        //设置全透明
        StatusBarUtil.setTransparent(this);
        aCache = ACache.get(context);
        progressDialog = new ProgressDialog(this);

        //开启位置服务，支持获取ble蓝牙扫描结果
        if (Build.VERSION.SDK_INT >= 23 && !isLocationOpen(getApplicationContext())) {
            Intent enableLocate = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivityForResult(enableLocate, REQUEST_LOCATION_PERMISSION);
        }else {
            mayRequestLocation();
        }

        if (BluetoothController.reBtGatt() == null) {

        }


        //注册蓝牙广播
        initBlueReceiver();
        //实例化BLE服务
        initService();
        //注册蓝BLE广播
        registerReceiver();
        //蓝牙监测并开始搜索
        searchBlue();
        //获取是否为某种模式下的跑步
        //getModel();

    }



    public void onClick(View view) {

    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    //注册广播，用于监听蓝牙状态
    public void initBlueReceiver() {
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(bluetoothState, filter);
        filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(bluetoothState, filter);
    }

    //接收蓝牙模块状态广播
    BroadcastReceiver bluetoothState = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String stateExtra = BluetoothAdapter.EXTRA_STATE;
            int state = intent.getIntExtra(stateExtra, -1);
            switch (state) {
                case BluetoothAdapter.STATE_TURNING_ON:
                    Log.i("蓝牙", "蓝牙模块正在打开");
                    break;
                case BluetoothAdapter.STATE_ON:
                    Log.i("蓝牙", "蓝牙已打开");

                    list.clear();//清空以前发现的蓝牙
                    if (!BluetoothController.getInstance().initBLE()) {///手机不支持蓝牙
                        Toast.makeText(MySportActivity.this, "您的手机不支持蓝牙",
                                Toast.LENGTH_SHORT).show();
                        return;//手机不支持蓝牙就啥也不用干了，关电脑睡觉去吧
                    }
                    progressDialog.showDialog();
                    new GetDataTask().execute();// 搜索任务

                    //-------------------------------------------------------------------------
                    Log.i("蓝牙", "搜索中");
                    break;
                case BluetoothAdapter.STATE_TURNING_OFF:
                    Log.i("蓝牙", "蓝牙模块正在关闭");
                    finish();
                    break;
                case BluetoothAdapter.STATE_OFF:
                    Log.i("蓝牙", "蓝牙模块处于关闭状态");
                    break;
            }
        }
    };

    //打开蓝牙，并搜索
    public void searchBlue() {
        if (mAdapter == null) {
            mAdapter = BluetoothAdapter.getDefaultAdapter();
        }
        if (!mAdapter.isEnabled()) {                       //判断蓝牙是否打开
            //initBlueReceiver();
            //弹出对话框提示用户是后打开
            Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enabler, REQUEST_BLE_PERMISSION);
            //不做提示，强行打开
            // mAdapter.enable();
        }else {
            if(isLocationOpen(getApplicationContext())){
                //new GetDataTask().execute();// 搜索
                getkLocation();  //授权
            }else{
                //openGPSSettings();
                Toast.makeText(MySportActivity.this,"请开启定位功能!",Toast.LENGTH_LONG).show();
                progressDialog.cancelDialog();
            }

        }

        if (mAdapter.isEnabled()) {                         //判断蓝牙是否连接
            //list.clear();//清空以前发现的蓝牙
            if (!BluetoothController.getInstance().initBLE()) {                 //手机不支持蓝牙
                Toast.makeText(MySportActivity.this, "您的手机不支持蓝牙",
                        Toast.LENGTH_SHORT).show();
                return;//手机不支持蓝牙就啥也不用干了，关电脑睡觉去吧
            }
            if (!BluetoothController.getInstance().isBleOpen()) {
                Toast.makeText(MySportActivity.this, "MainActivity",
                        Toast.LENGTH_SHORT).show();
                return;
            }
            new GetDataTask().execute();// 搜索任务
            progressDialog.showDialog();
        }
    }

    /**
     * 实例化服务
     */
    private void initService() {
        if(!isServiceRunning(context,"com.paobuji.aidebao.myapplication.ble.service.BLEService")){
            //开始服务
            intentService = new Intent(MySportActivity.this, BLEService.class);
            startService(intentService);
            //初始化蓝牙
            BluetoothController.getInstance().initBLE();
            Log.i("蓝牙","蓝牙启动");
        }

    }

    /**
     * 注册广播
     */
    private void registerReceiver() {
        receiver = new MsgReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConstantUtils.ACTION_UPDATE_DEVICE_LIST);
        intentFilter.addAction(ConstantUtils.ACTION_CONNECTED_ONE_DEVICE);

        registerReceiver(receiver, intentFilter);
    }


    //搜索蓝牙
    private class GetDataTask extends AsyncTask<Void, Void, String[]> {

        @Override
        protected String[] doInBackground(Void... params) {
            if (BluetoothController.getInstance().isBleOpen()) {
                BluetoothController.getInstance().startScanBLE();
            }

            Log.i("蓝牙", "开始扫描");
            return null;
        }
        @Override
        protected void onPostExecute(String[] result) {
            super.onPostExecute(result);
            Log.i("蓝牙", "扫描失败");
        }
    }

    /**
     * 接收广播，接收蓝牙模块发过来的值
     */
    public class MsgReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equalsIgnoreCase(
                    ConstantUtils.ACTION_UPDATE_DEVICE_LIST)) {
                String name = intent.getStringExtra("name");
                String address = intent.getStringExtra("address");
                boolean found = false;                                 //记录该条记录是否已在list中，
                for (EntityDevice device : list) {
                    if (device.getAddress().equals(address)) {
                        found = true;
                        break;
                    }
                }// for

                if (!found) {                                                       //发现蓝牙
                    Log.i("蓝牙", "发现蓝牙");
                   // toastLog("发现蓝牙");
                    EntityDevice temp = new EntityDevice();
                    temp.setName(name);
                    temp.setAddress(address);
                    list.add(temp);

                    getBlue(context, list);   //显示蓝牙列表
                }
            } else if (intent.getAction().equalsIgnoreCase(ConstantUtils.ACTION_CONNECTED_ONE_DEVICE)) {
                Log.i("蓝牙", "连接的蓝牙是："+intent.getStringExtra("name"));
                progressDialog.cancelDialog();
                finish();
            }
        }
    }


    //蓝牙的连接
    public void getBlue(final Context context, final ArrayList list) {
        if (deviceAdapter == null) {
            deviceAdapter = new DeviceAdapter(context, list);
            blueList.setAdapter(deviceAdapter);
            progressDialog.cancelDialog();
        } else {
            deviceAdapter.changeData(list);
        }

        blueList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                aCache .put("BleEntityDevice", (EntityDevice)list.get(i));
                if (BluetoothController.reBtGatt() == null) {
                    //连接设备
                    BluetoothController.getInstance().connect((EntityDevice) list.get(i));
                } else {
                    BluetoothController.clearBtGatt();
                    BluetoothController.getInstance().connect((EntityDevice) list.get(i));
                    progressDialog.showDialog();

                }
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //stopService(intentService);
        unregisterReceiver(receiver);
        unregisterReceiver(bluetoothState);

    }
    /*
       校验蓝牙权限
      */
    private static final int REQUEST_FINE_LOCATION = 0;
    private void mayRequestLocation() {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                //判断是否需要 向用户解释，为什么要申请该权限
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION))

                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_FINE_LOCATION);
                return;
            } else {

            }
        } else {

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_FINE_LOCATION:
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // The requested permission is granted.
                    new GetDataTask().execute();// 搜索任务
                } else {
                    // The user disallowed the requested permission.
                    finish();
                }
                break;
        }
    }

    /**
     * 判断位置信息是否开启
     * @param context
     * @return
     */
    public static boolean isLocationOpen(final Context context){
        LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        //gps定位
        boolean isGpsProvider = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        //网络定位
        boolean isNetWorkProvider = manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        return isGpsProvider|| isNetWorkProvider;
    }

    //定位授权
    public void getkLocation(){
        Log.i("蓝牙", " request location permission success");
        //Android6.0需要动态申请权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            try{
                //请求权限
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
                                Manifest.permission.ACCESS_FINE_LOCATION},
                        REQUEST_LOCATION_PERMISSION);
                if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                        Manifest.permission.ACCESS_COARSE_LOCATION)) {
                    //判断是否需要解释
                    //DialogUtils.shortT(getApplicationContext(), "需要蓝牙权限");
                }


            }catch (Exception e){

            }

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == REQUEST_BLE_PERMISSION){
            if(!mAdapter.isEnabled()){          //如果拒绝开启蓝牙则退出
                Log.i("蓝牙", "如果拒绝开启蓝牙则退出");
                finish();
            }else { //开启蓝牙检测定位权限
                if (isLocationOpen(getApplicationContext())) {
                    getkLocation();
                } else {
                    //若未开启位置信息功能，则退出该应用
                    Toast.makeText(MySportActivity.this,R.string.gps,Toast.LENGTH_LONG).show();
                    progressDialog.cancelDialog();
                }
            }
        }else if (requestCode == REQUEST_LOCATION_PERMISSION) {
            Log.i("蓝牙", " request location permission success  2");

        }
        super.onActivityResult(requestCode, resultCode, data);
    }


}
